package com.zy.mc_module.mvp.base;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

import java.lang.ref.WeakReference;

/**
 * Created on 18/10/20
 */
public class BasePresenter<V extends IView> implements IPresenter<V> {
    private WeakReference<V> mvpView;
    //订阅
    private CompositeDisposable mDisposables = new CompositeDisposable();

    /***
     * 绑定
     * @param view
     */
    @Override
    public void attachView(V view) {
        this.mvpView = new WeakReference<>(view);
    }

    /***
     * 解绑
     */
    @Override
    public void detachView() {
        if (null != mvpView) {
            mvpView.clear();
            mvpView = null;
        }
        //------取消订阅------
        //这个好像无效
        //SubscriptionManager.getInstance().cancel(mDisposables);
        //--------
        //这个有效
        if (mDisposables != null) {
            mDisposables.dispose();
            mDisposables.clear();
        }
    }

    public void clearView() {
        if (null != mvpView) {
            mvpView.clear();
            mvpView = null;
        }
        //------取消订阅------
        //这个好像无效
        //--------
        //这个有效
        if (mDisposables != null) {
            mDisposables.clear();
        }
    }

    /***
     * 获取mvpView
     */
    protected V getView() {
        //如果View 为null,就抛出异常
        if (!isViewAttached()) {
            throw new IllegalStateException("view not attached");
        } else {
            return mvpView.get();
        }
    }

    /***
     * 当前View/Fragment 是否存在
     * @return
     */
    protected boolean isViewAttached() {
        boolean istrue = false;
        if (null != mvpView) {
            if (null != mvpView.get()) {
                istrue = true;
            }
        }
        return istrue;
    }

    /***
     * 检查 是否还与View建立连接在,如果没有则抛出异常
     */
    protected void checkViewAttached() {
        if (!isViewAttached()) {
            throw new IllegalStateException("view not attached");
        }
    }

    /***
     * 添加集合
     * @param disposable
     */
    public void addDisposable(Disposable disposable) {
        mDisposables.add(disposable);
    }
}
